package test.check.system.remote;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import test.check.system.CheckSystem;

public class ServerAgent {
	public void startServerAgent(String ip, int port) throws InterruptedException {
		Socket socket = null;
		while(true) {
			try {
				socket = new Socket(ip, port);
			} catch (UnknownHostException e) {
				System.out.println("Server is not reachable.");
				Thread.sleep(1000*30);
			} catch (IOException e) {
				System.out.println("Server is not reachable.");
				Thread.sleep(1000*30);
			}
			
			if(socket != null && socket.isConnected()) {
				OutputStream os;
				try {
					os = socket.getOutputStream();
					InputStream is = socket.getInputStream();
					BufferedReader br = new BufferedReader(new InputStreamReader(is));
					PrintWriter pw = new PrintWriter(os);
					CheckSystem cs = new CheckSystem();
					String commandResult = null;
					
					pw.println("Check connection...\n");
					pw.flush();
					
					String line = null;
					while((line = br.readLine()) != null) {
						commandResult = cs.runCommand(line);
						pw.println(commandResult);
						pw.println("@result end");
						pw.flush();
					}
					
					br.close();
					pw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
